<template>
  <div class="public-stay-manage-action app-container">
    <div class="public-stay-manage-top">
      <div v-if="$route.query.action === 'add'">新增</div>
      <div v-else-if="$route.query.action === 'edit'">编辑</div>
      <div v-else-if="$route.query.action === 'detail'">详情</div>
      <div class="action-btn-box" v-if="$route.query.action !== 'detail'">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="handleAdd"
        >确定</el-button>
        <el-button
          plain
          size="mini"
          @click="goBack"
        >取消</el-button>
      </div>
      <div class="action-btn-box" v-else>
        <el-button
          plain
          size="mini"
          @click="() => { this.$router.go(-1) }"
        >返回</el-button>
      </div>
    </div>
    <div class="public-stay-manage-content">
      <div class="public-stay-manage-left">
        <div class="detail-title">房间信息</div>
        <el-form :model="queryParams" :rules="rules" label-position="top" ref="queryForm">
          <div class="top">
            <div class="left">
              <el-form-item label="房间号" prop="roomName">
                <el-input
                  v-model="queryParams.roomName"
                  placeholder="请输入房间号"
                  :disabled="$route.query.action === 'detail'"
                  clearable
                  size="small"
                  style="width: 450px"
                >
                </el-input>
              </el-form-item>
              <el-form-item label="原价" prop="originalPrice">
                  <el-input
                    v-model="queryParams.originalPrice"
                    placeholder="请输入原价"
                    :disabled="$route.query.action === 'detail'"
                    clearable
                    @input="(e) => getNumber(e, 'originalPrice')"
                    size="small"
                    style="width: 450px"
                  >
                    <template slot="append">元</template>
                  </el-input>
              </el-form-item>
              <el-form-item label="限制人数" prop="numberLimit">
                <el-input
                  v-model="queryParams.numberLimit"
                  placeholder="请输入限制人数"
                  :disabled="$route.query.action === 'detail'"
                  clearable
                  size="small"
                  style="width: 450px"
                >
                </el-input>
              </el-form-item>
              <el-form-item label="床型" prop="bedType">
                <el-select
                  v-model="queryParams.bedType"
                  placeholder="请选择床型"
                  :disabled="$route.query.action === 'detail'"
                  clearable
                  size="small"
                  style="width: 450px"
                >
                  <el-option
                    v-for="dict in bedList"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="用品" prop="applianceList">
                <el-checkbox
                  v-for="item,index in applianceList"
                  :value="item.check"
                  @change="(e) => checkChange('applianceList', index, e)"
                  :key="index"
                  :label="item.name"></el-checkbox>
              </el-form-item>
              <el-form-item label="媒体" prop="mediaList">
                <el-checkbox
                  v-for="item,index in mediaList"
                  :value="item.check"
                  @change="(e) => checkChange('mediaList', index, e)"
                  :key="index"
                  :label="item.name"></el-checkbox>
              </el-form-item>
            </div>

            <div class="right">
              <el-form-item label="房间类型" prop="roomType">
                <el-select
                  v-model="queryParams.roomType"
                  placeholder="请选择房间类型"
                  :disabled="$route.query.action === 'detail'"
                  clearable
                  size="small"
                  style="width: 450px"
                >
                  <el-option
                    v-for="dict in roomList"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="现价" prop="currentPrice">
                  <el-input
                    v-model="queryParams.currentPrice"
                    placeholder="请输入现价"
                    @input="(e) => getNumber(e, 'currentPrice')"
                    :disabled="$route.query.action === 'detail'"
                    clearable
                    size="small"
                    style="width: 450px"
                  >
                    <template slot="append">元</template>
                  </el-input>
              </el-form-item>
              <el-form-item label="窗户" prop="isWindow">
                <el-radio-group v-model="queryParams.isWindow" :disabled="$route.query.action === 'detail'">
                  <el-radio :label="1">有窗</el-radio>
                  <el-radio :label="0">无窗</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="早餐" prop="isBreakfast">
                <el-radio-group v-model="queryParams.isBreakfast" :disabled="$route.query.action === 'detail'">
                  <el-radio :label="1">含早餐</el-radio>
                  <el-radio :label="0">不含早餐</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="设施" prop="facilityList">
                <el-checkbox
                  v-for="item,index in facilityList"
                  :value="item.check"
                  @change="(e) => checkChange('facilityList', index, e)"
                  :key="index"
                  :label="item.name"></el-checkbox>
              </el-form-item>
              <el-form-item label="房间图片" required>
                <div class="upload-box">
                  <div class="file-box-view">
                    <el-image
                      v-if="fileData.roomImg"
                      :src="fileData.roomImg"
                      :preview-src-list="[fileData.roomImg]"
                    >
                    </el-image>
                  </div>
                  <el-upload
                      v-if="$route.query.action !== 'detail'"
                      :action="uploadUrl"
                      list-type="picture-card"
                      :before-upload="handleBeforeUpload"
                      :on-success="(response) => handleUploadSuccess('roomImg', response)"
                      :on-error="handleUploadError"
                      :on-remove="onRemoveHandel('roomImg')"
                      :headers="headers"
                      :show-file-list="false">
                      <i class="el-icon-plus"></i>
                  </el-upload>
                </div>
              </el-form-item>
            </div>
          </div>
        </el-form>
      </div>
    </div>

  </div>
</template>

<script>
import { updateFn, add, list } from "@/api/publicService/room";
import { getToken } from "@/utils/auth";

export default {
  name: "Logininfor",
  data() {
    return { 
      rules: {
          roomName: [
            { required: true, message: '请输入房间号', trigger: 'change' }
          ],
          numberLimit: [
            { required: true, message: '请输入限制人数', trigger: 'change' }
          ],
          originalPrice: [
            { required: true, message: '请输入原价', trigger: 'change' }
          ],
          currentPrice: [
            { required: true, message: '请输入现价', trigger: 'change' }
          ],
          bedType: [
            { required: true, message: '请选择床型', trigger: 'change' }
          ],
          roomType: [
            { required: true, message: '请选择房间类型', trigger: 'change' }
          ],
          isWindow: [
            { required: true, message: '请选择是否有窗', trigger: 'change' }
          ],
          isBreakfast: [
            { required: true, message: '请选择是否有早餐', trigger: 'change' }
          ],
          facilityList: [
            { required: true, message: '请选择设施', trigger: 'change' }
          ],
          applianceList: [
            { required: true, message: '请选择用品', trigger: 'change' }
          ],
          mediaList: [
            { required: true, message: '请选择媒体', trigger: 'change' }
          ],
      },
      // 遮罩层
      loading: true,
      uploadUrl: window.serverAPI.url + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      bedList: [],
      roomList: [],
      applianceList: [
        { name: '牙刷', key: 'isToothbrush' },
        { name: '牙膏', key: 'isToothpaste' },
        { name: '梳子', key: 'isComb' },
        { name: '沐浴露', key: 'isShowerGel' },
        { name: '洗发水', key: 'isShampoo' },
        { name: '纯净水', key: 'isPurifiedWater' },
        { name: '漱口水', key: 'isMouthwash' },
        { name: '水乳', key: 'isSkinfood' },
        { name: '精华', key: 'isEssence' },
        { name: '护发素', key: 'isHairConditioner' },
      ],
      facilityList: [
        { name: '拖鞋', key: 'isSlippers' },
        { name: '浴室', key: 'isBathroom' },
        { name: '卫生间', key: 'isToilet' },
        { name: '吹风机', key: 'isAirBlower' },
        { name: '浴缸', key: 'isBathtub' },
        { name: '空调', key: 'isAircondition' },
        { name: '新风', key: 'isFreshAir' },
        { name: '烤箱', key: 'isOven' },
        { name: '微波炉', key: 'isMicrowaveOven' },
        { name: '电磁炉', key: 'isInductionCooker' },
      ],
      mediaList: [
        { name: '电视机', key: 'isTv' },
        { name: '电脑', key: 'isComputer' },
        { name: '投影仪', key: 'isProjector' },
      ],
      fileData: {
        roomImg: undefined,
      },
      // 导出遮罩层
      exportLoading: false,
      // 查询参数
      queryParams: {
        applianceList: undefined,
        mediaList: undefined,
        facilityList: undefined,
        bedType: undefined,
        currentPrice: undefined,
        numberLimit: undefined,
        originalPrice: undefined,
        roomName: undefined,
        isBreakfast: undefined,
        isWindow: undefined,
        roomType: undefined
      }
    };
  },
  created() {
    this.getDict()
    this.$route.query.id && this.getList();
  },
  methods: {
    checkChange (key, idx, e) {
      let arr = [...this[key]]
      arr[idx].check = e
      let length = arr.filter(item => item.check).length
      this.queryParams[key] = length ? true : undefined
      this[key] = arr
    },
    getNumber (e, param) {
      this.queryParams[param] = e?.replace(/\D/g, '')
    },
    getList() {
      let {pageNum, pageSize, name, id} = this.$route.query
      list({
        pageNum, pageSize, name,
        zhusuId: this.$route.query.zhusuId,
      }).then(res => {
        let arr = res?.data?.rows || []
        let currentObj = arr.filter(item => item.id == id)?.[0] || {};
        let strList = ['mediaList', 'facilityList', 'applianceList'];
        strList.forEach(i => {
          this[i] = this[i].map(item => {
            return {
              ...item,
              check: !!currentObj[item.key]
            }
          })
        })
        this.queryParams = {
          applianceList: true,
          mediaList: true,
          facilityList: true,
          bedType: currentObj?.bedType || undefined,
          id: currentObj?.id || undefined,
          currentPrice: currentObj?.currentPrice || undefined,
          numberLimit: currentObj?.numberLimit || undefined,
          originalPrice: currentObj?.originalPrice || undefined,
          roomName: currentObj?.roomName || undefined,
          isBreakfast: currentObj?.isBreakfast,
          isWindow: currentObj?.isWindow,
          roomType: currentObj?.roomType || undefined,
        };
        this.fileData = {
          roomImg: currentObj?.roomImg || undefined,
        };

      });
    },
    getDict() {
      this.getDicts("zhusu_bed_type").then(response => {
        this.bedList = response.data;
      });
      this.getDicts("zhusu_room_type").then(response => {
        this.roomList = response.data;
      });
    },
    // 景区列表
    getJingQuList() {
      jingQuListApi()
        .then((res) => {
          if (res.code === 200) {
            this.jingQuList = res.data.map((v) => {
              return {
                value: v.jingquId,
                label: v.jingquName,
              };
            });
          }
        })
    },
    // 使用 before-upload 限制用户上传的图片格式和大小。
    handleBeforeUpload(file) {
      // 校检文件大小
      const isLt = file.size / 1024 / 1024 < 8;
      if (!isLt) {
        this.$message.error(`上传文件大小不能超过8MB!`);
        return false;
      }
      // 检验格式
      let type = file.type;
      let jpg = type.indexOf("jpg");
      let png = type.indexOf("png");
      let jpeg = type.indexOf("jpeg");
      if (jpg == -1 && png == -1 && jpeg == -1) {
        this.$message.error(`上传文件格式为jpg，png，jpeg!`);
        return false;
      }

      return true;
    },

    // 文件上传成功钩子
    handleUploadSuccess(param, response) {
      if (response.code === 200) {
        this.fileData[param] = response.data.url
      }
    },

    // 删除已上传的文件
    onRemoveHandel(param) {
      this.queryParams[param] = ''
    },

    // 文件上传失败
    handleUploadError() {
      this.$message.error("图片插入失败");
    },
    handleAdd() {
      this.$refs.queryForm.validate((tag) => {
        if (tag) {
          if (!this.fileData.roomImg) {
            return this.$message.error("请上传图片");
          } else {
            let arr = [...this.applianceList, ...this.mediaList, ...this.facilityList];
            let obj = {};
            arr.forEach(item => {
              obj[item.key] = item.check ? 1 : 0
            })
            obj = {
              zhusuId: this.$route.query.zhusuId,
              ...obj,
              ...this.queryParams,
              ...this.fileData,
            }
            delete obj.applianceList
            delete obj.mediaList
            delete obj.facilityList
            let fun = this.$route.query.id ? updateFn : add
            fun(obj).then(res => {
              if (res?.code === 200) {
                this.$message.success("保存成功");
                this.goBack();
              } else {
                this.$message.error(res?.msg);
              }
            })
          }
        }
      });
    },
    goBack() {
      this.$router.go(-1);
    },
  }
};
</script>


<style rel="stylesheet/scss" lang="scss">
.public-stay-manage-action {
  .public-stay-manage-top {
    border-bottom: 1px solid #F2F3F5;
    display: flex;
    justify-content: space-between;
    padding: 12px;
    align-items: center;
  }
  .public-stay-manage-content {
    display: flex;
    .detail-title {
      position: relative;
      padding-left: 12px;
      padding-block: 20px;
      &::after {
        content: '';
        width: 4px;
        height: 16px;
        background: #3370FF;
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        margin: auto 0;

      }
    }
  }
  .top, .bottom {
    display: flex;
    .left {
      width: 650px;
    }
    .right {
      flex: 1;
    }
  }
  .upload-box {
    display: flex;
    .file-box-view{
      height: 146px;
      width: 146px;
      margin-right: 10px;
      display: flex;
      justify-content: center;
      align-items: center;
      img{
        max-height: 100px;
        max-width: 100px;
      }
    }
  }
}
</style>